package com.pz.gulimall.auth.service;

import com.pz.gulimall.auth.feign.MemberFeign;
import com.pz.gulimall.common.exception.BizCodeEnum;
import com.pz.gulimall.common.exception.RRException;
import com.pz.gulimall.common.to.UserInfoTo;
import com.pz.gulimall.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class UserService {
    @Autowired
    private MemberFeign memberFeign;

    /**
     * 获取用户的详细信息包括 ums_member、ums_member_receive_address、ums_member_statistics_info
     *
     * @param userId 数据库用户唯一标识
     * @return
     */
    public R getUserInfo(long userId) {
        try {
            R ans = memberFeign.info(userId);
            if(ans.getCode() == 0){
                return R.ok().put("data", ans.get("data"));
            } else {
                throw new RRException(ans.getMsg(), ans.getCode());
            }
        } catch (Exception e) {
            throw new RRException(BizCodeEnum.AUTH_RPC_MEMBER_FAILED.getMsg(), BizCodeEnum.AUTH_RPC_MEMBER_FAILED.getCode());
        }
    }

    public R updateUserInfo(UserInfoTo userInfo) {
        try {
            R r = memberFeign.updateUserInfo(userInfo);
            if(r.getCode() == 0){
                return R.ok();
            } else {
                return R.error(r.getCode(),r.getMsg());
            }
        } catch (Exception e) {
            throw new RRException(BizCodeEnum.AUTH_RPC_MEMBER_FAILED.getMsg(), BizCodeEnum.AUTH_RPC_MEMBER_FAILED.getCode());
        }
    }

    public R delAddress(Long[] ids) {
        try {
            R r = memberFeign.deleteAddress(ids);
            if(r.getCode() == 0){
                return R.ok("删除成功！");
            } else {
                return R.error(r.getCode(),r.getMsg());
            }
        } catch (Exception e) {
            throw new RRException(BizCodeEnum.AUTH_RPC_MEMBER_FAILED.getMsg(), BizCodeEnum.AUTH_RPC_MEMBER_FAILED.getCode());
        }
    }

    public R addAddress(Long userId, Map<String, Object> address) {
        if(userId != null && address!=null){
            address.put("memberId", userId);
            try {
                R r = memberFeign.saveAddress(address);
                if(r.getCode() == 0){
                    return R.ok("添加成功！");
                } else {
                    return R.error(r.getCode(),r.getMsg());
                }
            } catch (Exception e) {
                throw new RRException(BizCodeEnum.AUTH_RPC_MEMBER_FAILED.getMsg(), BizCodeEnum.AUTH_RPC_MEMBER_FAILED.getCode());
            }
        } else {
            return R.error();
        }
    }
}
